home *** CD-ROM | disk | FTP | other *** search
Text File | 1994-11-28 | 2.7 KB | 84 lines | [TEXT/R*ch] |
- Unit BGHSorting;
- Interface
-
- procedure sort(
- left, right: longint;
- function less_than(a,b:longint):boolean;
- procedure swap(a,b:longint)
- );
-
- Implementation
-
- procedure sort(
- left, right:longint;
- function less_than(a,b:longint):boolean;
- procedure swap(a,b:longint)
- );
- var
- i, j, mid, median, small_pos: longint;
- begin
- while (right-left) >= 15 do begin
- mid := (left+right) div 2;
-
- {find the Median of left, mid, right}
- if less_than(left,mid) then begin
- if less_than(mid,right) then median := mid
- else if less_than(left,right) then median := right
- else median := left
- end else begin
- if less_than(left,right) then median := left
- else if less_than(mid,right) then median := right
- else median := mid;
- end; {finding the median}
-
- {
- partition the region into three:
-
- left <= x <= j: those smaller than median
- j < x < i: those equal to median
- i <= x <= right: those greater than median
- }
- i := left;
- j := right;
- while i <= j do begin
- while (i<right) & less_than(i,median) do i := i + 1;
- while (j>left) & less_than(median,j) do j := j - 1;
- if i <= j then begin
- if i < j then begin
- {watch for median getting moved under us!}
- if median = i then median := j
- else if median = j then median := i;
- swap(i,j);
- end;
- {no need to look at these two again}
- i := i + 1;
- j := j - 1;
- end;
- end;
- {skip over any items equal to the guess of the median}
- while (i<right) & not less_than(median,i) do i := i + 1;
- while (j>left) & not less_than(j,median) do j := j - 1;
-
- {now sort the two halves}
- if (j-left) < (right-i) then begin
- {the left half is smaller -- sort it recursively first}
- sort(left,j,less_than,swap);
- left := i; {prepare for next iteration}
- end else begin
- {the right half is smaller -- sort it recursively first}
- sort(i,right,less_than,swap);
- right := j; {prepare for next iteration}
- end;
- end; {while more than xxx elements to sort}
-
- {now selection sort any remaining elements}
- for i := left to right-1 do begin
- small_pos := i;
- for j := i+1 to right do if less_than(j,small_pos) then small_pos := j;
- if small_pos <> i then swap(i,small_pos);
- end;
-
- end; {sort}
-
- end.
-